﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using UnityEngine;

public delegate void TimeDo();

/// <summary>
/// 计时类
/// </summary>
public class Timer
{
    public float IntervalTime { get; }
    public bool IsLoop { get; }
    public TimeData TimeData { get; }

    private TimeDo TimeDo = () => { };
    /// <summary>
    /// 虚伪的等待时间(经过时间缩放处理)
    /// </summary>
    public float WaitTime { get; private set; } = 0;
    /// <summary>
    /// 真实的累计时间(未经时间缩放处理)
    /// </summary>
    public float TotalTime { get; private set; } = 0;
    public bool isRun { get; private set; } = true;

    /// <summary>
    /// 初始化计时类
    /// </summary>
    /// <param name="waitTime">等待时间</param>
    /// <param name="isLoop">是否循环计时</param>
    /// <param name="timeScale">时间缩放倍率</param>
    /// <param name="timeDo">到时委托</param>
    public Timer(float intervalTime, bool isLoop, TimeData timeData, TimeDo timeDo)
    {
        this.IntervalTime = intervalTime;
        this.IsLoop = isLoop;
        this.TimeData = timeData;
        this.TimeDo = timeDo;

    }

    /// <summary>
    /// 初始化计时类
    /// </summary>
    /// <param name="waitTime">等待时间</param>
    /// <param name="isLoop">是否循环计时</param>
    /// <param name="timeScale">时间缩放倍率</param>
    public Timer(float intervalTime, bool isLoop, TimeData timeData)
    {
        this.IntervalTime = intervalTime;
        this.IsLoop = isLoop;
        this.TimeData = timeData;

    }

    public void SetTimeDo(TimeDo timeDo)
    {
        this.TimeDo = timeDo;
    }

    public bool AddTime(float time)
    {

        WaitTime += time * TimeData.LocalTimeScale;
        TotalTime += time;
        if (WaitTime >= IntervalTime)
        {
            TimeDo.Invoke();
            WaitTime = 0;
            return true;
        }
        return false;
    }

    public void Start()
    {
        WaitTime = 0f;
        TotalTime = 0f;
        TimerManager.Instance.AddTimer(this);
    }

    public void Pasue()
    {
        isRun = false;
    }

    public void Continue()
    {
        isRun = true;
    }

    public void End()
    {
        TimerManager.Instance.RemoveTimer(this);
    }
}
